<template>
  <div class="new">
    <!--<affix :label="$t('business.newBusiness')" :showTitle="showTitle" v-if="businessTypeArr.length !==0">-->

  <!--</affix>-->
    <div v-if="businessTypeArr.length !==0" class="new-business new-business-webchat">
      <el-form label-position="top" :model="form"  ref="form" :rules="rules" class="newbusiness-form">
        <p class="title"></p>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="$t('business.businessFlow')" class="business-type" required>
              <el-select size="mini" v-model.trim="form.flow" filterable placeholder="" @change="businessTypeChange" style="width:100%">
                <el-option  v-for="item in businessTypeArr"
                            :label="item.label"
                            :key="item.value"
                            :value="item.value">
                  <!--<span>{{item.label}}</span>-->
                  <!--<span style="color:#999" v-if="item.busSumTime">(总时长{{item.busSumTime}})</span>-->
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('business.priorityLabel')">
              <el-radio-group v-model.trim="form.priority" @change="priorityChange">
                <el-radio size="mini" :label="'1'">{{this.$t('business.priority1')}}</el-radio>
                <el-radio size="mini" :label="'2'" class="business-priority2">{{this.$t('business.priority2')}}</el-radio>
                <el-radio size="mini" :label="'3'" class="business-priority3">{{this.$t('business.priority3')}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <base-form :items="items"
                   ref="stepFields"
                   @cacheFields="cacheFields"
                   @showBigImg="showBigImg">
        </base-form>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item :label="$t('business.nextStep')">
              <el-select size="mini" v-model.trim="form.nextAction" filterable placeholder="" @change="nextStepChange" class="width-full">
                <el-option  v-for="item in nextAction"
                            :label="item.label"
                            :key="item.value"
                            :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('business.handlePeople')" prop="nextUser">
              <el-select size="mini" v-model.trim="form.nextUser" filterable placeholder="" class="width-full">
                <el-option  v-for="item in dealAgent"
                            :label="item.label"
                            :key="item.value"
                            :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <span class="follow-label fl">{{$t('business.followedAgentsSetting')}}</span>
            <div class="follow-agent-wrap">
              <span class="follow-agent follow-common" v-for="item in folllowedAgents" :key="item._id">{{item.label}}<i class="el-icon-close" @click.stop="closeFollowedAgents(item._id)"></i></span>
              <el-popover
                ref="popover4"
                placement="bottom"
                @show="popoverShow"
                width="240"
                trigger="click">
                <agent-tree :readSeat="folllowedAgents" ref="agentTree" @saveFollowedAgents="saveFollowedAgents"></agent-tree>
              </el-popover>
              <span class="follow-agent-add follow-common"  v-popover:popover4><i class="el-icon-plus"></i> {{$t('public.add')}}</span>
            </div>
          </el-col>
           <el-col :span="24">
            <related-bussiness :relatedBusiness="form.relatedBusiness" :relatedBusinessShow="true" @saveRelatedBusiness="saveRelatedBusiness" @closeRelatedBusiness="closeRelatedBusiness"></related-bussiness>
          </el-col>
          <!-- 关联会话 -->
          <el-col :span="24">
            <related-session :relatedWebchats="form.relatedWebchats" :relatedSessionShow="true" @saveRelatedSession="saveRelatedSession" @closeRelatedSession="closeRelatedSession"></related-session>
          </el-col>
          <!-- 关联通话 -->
          <el-col :span="24">
            <related-call :relatedCallSheet="form.relatedCallSheet" :relatedCallShow="true" @saveRelatedCall="saveRelatedCall" @closeRelatedCall="closeRelatedCall"></related-call>
          </el-col>
          <el-col :span="24">
            <affix :label="'处理工单-' + nextStepName" :bodyStyle="{'padding-bottom': '0px'}" v-if="actionItems.length"></affix>
            <base-form ref="actionFields" :items="actionItems" @cacheFields="actionCacheFields" @showBigImg="showBigImg"></base-form>
          </el-col>
        </el-row>
      </el-form>
      <div class="btn-wraper clearBoth">
        <div class="btns">
          <el-button class="primary_btn" @click.stop="submit('temp')" :disabled="disabledBtn">{{$t('business.staging')}}</el-button>
          <el-button type="primary" class="primary_btn" @click.stop="submit('new')" :disabled="disabledBtn">{{$t('business.submit')}}</el-button>
        </div>
      </div>
    </div>
    <div v-else class="no-power">{{$t('business.noBusinessPower')}}</div>
  </div>
</template>
<script>
  import affix from '../../../../ui-modules/affix/Affix.vue'
  import BaseForm from '../base/BaseForm'
  import AgentTree from '../agentTree.vue'
  import {throttle} from 'lodash'
  import {getCache, deepClone} from '@/utils/m7Utils.js'
  import { commitImgType2 } from '@/utils/publicMethod.js'
  import {formRollToFirstError} from '../../../../../utils/validate.js'
  import relatedBussiness from '../relatedBussiness.vue'
  import relatedSession from '../relatedSession.vue'
  import relatedCall from '../relatedCall.vue'
  import {fieldsExtend, taskTimeAll, getRoleAgents, getRoleActions, getStepRoles, getStepQueues, getQueueAgents,getFlowAction, getStartStep, hasAccessForFlow, getObjectById, getDefaultFromCustomer} from '@/utils/workflowUtils.js'
  export default {
    name: 'newBusiness',
    data () {
      return {
        form: {
          flow: '',
          nextAction: '',
          nextUser: '',
          priority: '1',
          followedAgents: [],
          relatedBusiness:[],
          relatedWebchats:[],
          relatedCallSheet:[],
        },
        items: [
        ],
        actionItems: [],
        nextAction: [],
        dealAgent: [],
        disabledBtn: false,
        businessTypeArr: [],
        rules: {
          nextUser: [
            {required: true, message: this.$t('business.masterRequierd'), trigger: 'change'}
          ]
        },
        nextStepName: '',
        flowTemplate: {},
      }
    },
    props: {
      cid: String,
      callId: String,
      custInfo: {type: Object, default: function () { return {} }},
      cdrCall: {type: Boolean, default: false}, // 来电
      detail: {type: Object, default: function () { return {} }},
      cacheId: {type: String, default: ''} // 缓存工单信息的id
    },
    components: {
      affix,
      BaseForm,
      AgentTree,
      relatedBussiness,
      relatedSession,
      relatedCall
    },
    methods: {
      //保存关联工单
      saveRelatedBusiness(searchContent){
        if(!this.form.relatedBusiness.includes(searchContent)){
          this.form.relatedBusiness.push(searchContent)
        }else{
          this.$message.error(this.$t('business.businessTip2'))
        }
      },
      //删除关联工单
      closeRelatedBusiness(number){
        let index = this.form.relatedBusiness.indexOf(number)
        this.form.relatedBusiness.splice(index,1)
      },
       //保存关联会话
      saveRelatedSession(searchContent){
        // 不能添加本身
        if(this.cacheId && this.cacheId === searchContent){
          this.$message.error(this.$t('business.businessTip8'))
        }else{
          if(!this.form.relatedWebchats.includes(searchContent)){
            this.form.relatedWebchats.push(searchContent)
          }else{
            this.$message.error(this.$t('business.businessTip3'))
          }
        }
      },
      //删除关联会话
      closeRelatedSession(number){
        let index = this.form.relatedWebchats.indexOf(number)
        this.form.relatedWebchats.splice(index,1)
      },
      // 保存关联通话
      saveRelatedCall(searchContent){
        if(!this.form.relatedCallSheet.includes(searchContent)){
          this.form.relatedCallSheet.push(searchContent)
        }else{
          this.$message.error(this.$t('business.businessTip4'))
        }
      },
      // 删除关联通话
      closeRelatedCall(number){
        let index = this.form.relatedCallSheet.indexOf(number)
        this.form.relatedCallSheet.splice(index,1)
      },
      showBigImg (data) {
        // 获取所有包含imgA的图片
        let _array = this.$el.querySelectorAll('.new-business-webchat .imgA')
        commitImgType2(data, _array)
      },
      showHistory () {
        this.$emit('openHistory', true)
      },
      /**
       * 工单类型变化
       * @param {Boolean} isCache 是否从缓存里取
       */
      businessTypeChange (_id, isCache) {
        this.items = []
        this.actionItems = []
        let busCache = this.$getCache('busCache') || {}
        if (!isCache && this.cacheId) {
          busCache[this.cacheId] = {flow: _id}
        }
        this.$nextTick(() => {
          let currentBusCache = busCache[this.cacheId] || {} // 当前cacheId缓存的数据
          let flow = getCache('businessFlow', _id)
          let step = getStartStep(flow)
          this.flowTemplate = Object.freeze(flow)
          this.form = {
            flow: _id,
            nextAction: '',
            nextUser: '',
            priority: currentBusCache.priority || '1',
            followedAgents: currentBusCache.followedAgents || [],
            relatedBusiness: currentBusCache.relatedBusiness || [],
            relatedWebchats: currentBusCache.relatedWebchats || [],
            relatedCallSheet: currentBusCache.relatedCallSheet || []
          }
          this.items = deepClone(step.stepFields || [])
          // 定义客户字段顺序
//          this.items = step.stepFields || []
          // 客户字段，定义内容样式
          let flowFields = flow ? flow.fields : []
          let actions = getRoleActions(step)
          this.nextAction = []
          for (let i = 0; i < actions.length; i++) {
            this.nextAction.push({label: actions[i].name, value: actions[i]._id, specific: actions[i].specific})
          }
          if (this.nextAction.length !== 0) {
            this.form.nextAction = (this.cacheId && busCache[this.cacheId].nextActionId) || this.nextAction[0].value
            this.nextStepChange(this.form.nextAction, isCache)
          }
          for (let i = 0; i < this.items.length; i++) {
            let row = this.items[i]
            for (let j = 0; j < row.cols.length; j++) {
              let col = row.cols[j]
              for (let k = 0; k < col.fields.length; k++) {
                let field = col.fields[k]
                let cacheField = getObjectById(flowFields, field._id) || {}
                if (cacheField.type === 'dropdown' || cacheField.type === 'dropdownTree') {
                  if (currentBusCache[cacheField._id]) {
                    // 如果缓存中有数据，从缓存中取
                    let value = currentBusCache[cacheField._id]
                    let value1 = currentBusCache[cacheField._id + '_1'] || ''
                    let value2 = currentBusCache[cacheField._id + '_2'] || ''
                    let value3 = currentBusCache[cacheField._id + '_3'] || ''
                    let value4 = currentBusCache[cacheField._id + '_4'] || ''
                    cacheField['default'] = [value, value1, value2, value3, value4]
                  } else if (cacheField.trigger === 'phoneAddress') {
                    // 客户联系电话所属地
                    let address = this.custInfoToForm(cacheField)
                    cacheField['default'] = [address.provinces || cacheField['default'], address.city]
                  } else if (cacheField.relevance && cacheField.relevance !== 'no') {
                    // 关联客户信息
                    cacheField['default'] = getDefaultFromCustomer(cacheField, this.custInfo) || []
                  } else {
                    cacheField['default'] = [cacheField['default']]
                  }
                } else if (cacheField.type === 'checkbox') {
                  if (currentBusCache[cacheField._id]) {
                    cacheField['default'] = currentBusCache[cacheField._id]
                  } else if (cacheField.relevance && cacheField.relevance !== 'no') {
                    cacheField['default'] = getDefaultFromCustomer(cacheField, this.custInfo) || []
                  } else {
                    cacheField['default'] = [cacheField['default']]
                  }
                } else {
                  if (currentBusCache[cacheField._id]) {
                    cacheField['default'] = currentBusCache[cacheField._id]
                  } else if (cacheField.relevance && cacheField.relevance !== 'no') {
                    cacheField['default'] = getDefaultFromCustomer(cacheField, this.custInfo) || ''
                  } else {
                    cacheField['default'] = cacheField['default']
                  }
                }
                Object.assign(field, cacheField)
              }
            }
          }
        })
      },
      // 工单动作变更
      async nextStepChange (_id, isCache) {
        let flow = getCache('businessFlow', this.form.flow)
        let step = getStartStep(flow)
        let action = getFlowAction(step._id, _id)
        let nextStepId = action.jumpTo
        let nextStep = getCache('businessFlowStep', nextStepId) || {}
        this.nextStepName = action.name
        let busCache = this.$getCache('busCache')
        if (!isCache && this.cacheId) {
          busCache[this.cacheId + 'nextAction'] = {}
          busCache[this.cacheId].nextActionId = _id
        }
        let currentStepCache = busCache[this.cacheId + 'nextAction']
        this.actionItems = fieldsExtend(deepClone(action.actionFields), this.flowTemplate.fields, (cacheField) => {
          if (cacheField.type === 'dropdown' || cacheField.type === 'dropdownTree') {
            return cacheField['default'] = ['', '', '', '', ''].map((item, index) => {
              return !index ? (currentStepCache[cacheField._id] ||cacheField['default'])
                : (currentStepCache[cacheField._id + `_${index}`] || '')
            })
          } else if (cacheField.type === 'checkbox') {
            return cacheField['default'] = currentStepCache[cacheField._id] || [cacheField['default']]
          } else {
            return cacheField['default'] = currentStepCache[cacheField._id] ||
              cacheField['default']
          }
        })
        if (nextStep.type !== 'sys' && action.specific) {
          // specific为true，必须指定处理人
          this.rules.nextUser[0].required = true
        } else {
          this.rules.nextUser[0].required = false
        }
        console.log(nextStep,'nextStep')
        
        let roles = getStepRoles(nextStepId)
        let queues = getStepQueues(nextStepId)
        let queueAgents = []
        let roleAgentList = []
        let queueAgentList = []
        roleAgentList = getRoleAgents(roles, true, this.$store.state.session.user._id)
          queueAgentList = await getQueueAgents(queues, true)
        let agents = [...new Set(roleAgentList.concat(queueAgentList))]
        console.log(agents,'agents')
        this.dealAgent = []
        if (agents.length !== 1) {
          this.dealAgent.push({label: this.$t('public.autoAssign'), value: ''})
        }
        for (let i = 0; i < agents.length; i++) {
          this.dealAgent.push({label: agents[i].displayName + '[' + agents[i].exten + ']', value: agents[i]._id})
        }
        if (nextStep.defaultAgent && this.dealAgent.length) {
          if (nextStep.defaultAgent === 'busCreateUser') {
            nextStep.defaultAgent = this.$store.state.session.user._id
          }
          let defaultAgent = this.dealAgent.filter((item) => {
            if (item.value === nextStep.defaultAgent) {
              return true
            }
          })
          this.form.nextUser = defaultAgent[0] ? defaultAgent[0].value : this.dealAgent[0].value
        } else {
          this.form.nextUser = this.dealAgent[0] ? this.dealAgent[0].value : ''
        }
      },
      // 生成工单类型数据
      businessTypeData () {
        let flows = getCache('businessFlow')
        let data = []
        for (var i = 0; i < flows.length; i++) {
          let flowsItem = flows[i]
          if (hasAccessForFlow(flowsItem)) {
            let busSumTime = null
            if (flowsItem.ctype && flowsItem.ctime) {
              busSumTime = taskTimeAll(flowsItem.ctype, flowsItem.ctime)
            }
            if (busSumTime) {
              data.push({value: flowsItem._id, label: flowsItem.name + '(' + this.$t('business.totalTimeStateComplete') + busSumTime + ')', busSumTime: busSumTime})
            } else {
              data.push({value: flowsItem._id, label: flowsItem.name, busSumTime: busSumTime})
            }
          }
        }
        return data
      },
      // 从客户信息里取数据填充到工单form
      custInfoToForm (cacheField) {
        let address = this.$getCache('options', cacheField.dic) || {}
        let phone = (this.custInfo && this.custInfo.phone) || []
        let addressId = {provinces: '', city: ''}
        let area = phone[0] ? phone[0].area : ''
        if (area) {
          let area1 = area.substr(0, 2)
          address.options.some((item) => {
            if (item.name.indexOf(area1) !== -1) {
              addressId.provinces = item.key
              let area2 = ''
              if (area1 === '内蒙' || area1 === '黑龙') {
                area2 = area.substr(3)
              } else {
                area2 = area.substr(2)
              }
              item.options.some((one) => {
                if (one.name.indexOf(area2) !== -1) {
                  addressId.city = one.key
                  return true
                }
              })
              return true
            }
          })
        }
        return addressId
      },
      // 暂存工单请求
      doSaveTempBusiness (data) {
        this.form.customer = this.cid
        this.$emit('event', {event: 'addTempBusinessTask', data: {customer: this.cid, form: Object.assign(data, this.form)}})
      },
      submit: throttle(function (type) {
        let data = {}
        let pass = false
        let stepFields = this.$refs.stepFields.submit(type === 'temp')
        let actionFields = this.$refs.actionFields.submit(type === 'temp')
        if (actionFields && stepFields) {
          Object.assign(data, stepFields)
          if (Object.keys(actionFields).length) {
            data.actionFields = actionFields
          }
          pass =  true
        }
        if (pass && type === 'new') {
          this.doSaveBusiness(data)
        } else if (pass && type === 'temp') {
          this.doSaveTempBusiness(data)
        } else if (!pass) { // 校验不通过
          formRollToFirstError(this.$refs.form.$el) // 表单校验有问题时，滚动到第一个el-error的位置
        }
      }, 1100, {trailing: false}),
      // 缓存事件
      cacheFields (data) {
        let busCache = this.$getCache('busCache')
        if (busCache[this.cacheId]) {
          Object.assign(busCache[this.cacheId], data.data)
        }
      },
      // 缓存工单开始步骤动作界面
      actionCacheFields (data) {
        let busCache = this.$getCache('busCache')
        if (busCache[this.cacheId + 'nextAction']) {
          Object.assign(busCache[this.cacheId + 'nextAction'], data.data)
        }
      },
      // 提交工单请求
      doSaveBusiness (data) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.form.customer = this.cid
            this.$emit('event', {event: 'addBusinessTask', data: {customer: this.cid, form: Object.assign(data, this.form)}})
          }
        })
      },
      // 删除关注人
      closeFollowedAgents (agent) {
        this.form.followedAgents = this.form.followedAgents.filter((item) => item !== agent)
      },
      // 保存关注人
      saveFollowedAgents (agents) {
        this.form.followedAgents = deepClone(agents)
      },
      // 工单优先级change
      priorityChange (value) {
        this.cacheFields({data: {priority: value}})
      },
      // 打开坐席树时，选中已关注人
      popoverShow () {
        this.$refs.agentTree.setCheckedKeys()
      },
      // 重置表单
      refreshForm (flow) {
        // flow 为undefined 说明没有该cachId下的缓存
        // 上一次提交的工单
        let businessTypeDefault = window.localStorage.businessTypeDefault
        businessTypeDefault = businessTypeDefault && this.businessTypeArr.some(item => item.value === businessTypeDefault) ? businessTypeDefault : ''
        if (this.businessTypeArr.length) {
          this.businessTypeChange(flow || businessTypeDefault || this.businessTypeArr[0].value, flow)
        }
      }
    },
    computed: {
      folllowedAgents () {
        let agents = this.form.followedAgents || []
        let agentsAll = this.$agentsMap() || {}
        return agents.map((item) => {
          return {_id: item, label: agentsAll[item].displayName}
        })
      }
    },
    watch: {
      folllowedAgents () {
        this.cacheFields({data: {followedAgents: this.form.followedAgents || []}})
      }
    },
    beforeMount () {
    },
    mounted () {
      Promise.all([
        this.$store.dispatch('getCache', {type: 'options'}), this.$store.dispatch('getCache', {type: 'agents'})
      ]).then(([res1, res2]) => {
        this.businessTypeArr = this.businessTypeData()
        if (this.businessTypeArr.length === 0) {
          return
        }
        let hasAccessForeFlowFlag = false
        let callBussinessTypeArr = JSON.parse(window.sessionStorage.getItem('callBussinessTypeId')) || []
        console.log(callBussinessTypeArr)
        // 获取工单缓存信息
        let busCache = this.$getCache('busCache') || {}
        let flow = busCache[this.cacheId] && busCache[this.cacheId].flow
        // 上一次提交的工单
        let businessTypeDefault = window.localStorage.businessTypeDefault
        businessTypeDefault = businessTypeDefault && this.businessTypeArr.some(item => item.value === businessTypeDefault) ? businessTypeDefault : ''
        if (this.cdrCall && this.callId && callBussinessTypeArr.length > 0) { // 来电模块 && 配置对接工单
          for (let i = 0; i < callBussinessTypeArr.length; i++) {
            for (let j = 0; j < this.businessTypeArr.length; j++) {
              console.log(this.businessTypeArr[j]._id)
              if (callBussinessTypeArr[i].businessTypeId === this.businessTypeArr[j].value) { // 有工单权限
                if (callBussinessTypeArr[i].id === this.callId) { // 是当前的通话
                  this.businessTypeChange(flow || callBussinessTypeArr[i].businessTypeId || businessTypeDefault, flow)
                  this.form.flow = callBussinessTypeArr[i].businessTypeId
                  hasAccessForeFlowFlag = true
                  break
                }
              }
            }
          }
          if (!hasAccessForeFlowFlag) { // 当前工单对接没有工单权限或者是被停用
            this.businessTypeChange(flow || businessTypeDefault || this.businessTypeArr[0].value, flow)
            this.form.flow = this.businessTypeArr[0].value
          }
        } else {
          // 显示优先级 缓存的工单>上次提交的工单>默认工单
          this.businessTypeChange(flow || businessTypeDefault || this.businessTypeArr[0].value, flow)
          this.form.flow = this.businessTypeArr[0].value
        }
      })
    }
  }
</script>
<style lang="stylus" scoped>
    @import '../../../../../assets/common.styl'

    .new 
      position relative
    .new-business
      position relative
      height calc(100vh - 243px)
      box-sizing border-box
      overflow-y hiden
      transform: scale(1, 1);//加入transform样式，子元素根据父元素固定定位
      .btn-wraper
        position fixed
        bottom 0
        width 100%
        padding 12px 20px 12px 0px
        box-sizing border-box
        background rgba(250,250,250,1)
        box-shadow 0px 0px 8px rgba(0,0,0,0.15)
        .btn-postion
          float right
        .btns
          text-align center
    .title
      padding-top 18px
    .newbusiness-form
      position relative
      height calc(100vh - 300px)
      padding 0 20px
      overflow-y auto
      overflow-x hidden
    .no-power
      color $cf-blue
      font-weight bolder
      padding 20px 20px
    .business-type
      padding 0px 0 5px
    .width-full
      width 100%
    .btn-wraper
      .save
        background $c-sub
    .follow-label
      line-height 24px
      font-size 12px
    .follow-agent-wrap
      padding-left 72px
      .follow-common
        float left
        position relative
        line-height 24px
        margin 0 0 10px 10px
        padding 0 10px
        border-radius 4px
      .follow-agent-add
        border 1px solid $c-main
        color $c-main
        cursor pointer
      .follow-agent
        line-height 26px
        background-color $c-bus-label
        color #fff
        &:hover
          .el-icon-close
            display block
        .el-icon-close
          display none
          position absolute
          right -10px
          top -10px
          width 24px
          height 24px
          font-size 16px
          line-height 24px
          transform scale(0.6)
          text-align center
          color #fff
          background-color $c-pink
          border-radius 50%
          border 1px solid #fff
          cursor pointer
</style>
